package com.hzdesk.media.matvector.koreabatch.client.my_paperless.fragment.Fragment_persenter;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hzdesk.media.matvector.koreabatch.client.my_paperless.R;
import com.hzdesk.media.matvector.koreabatch.client.my_paperless.adapter.CursorColorAdapter;
import com.hzdesk.media.matvector.koreabatch.client.my_paperless.adapter.DevicesManagerAdapter;
import com.hzdesk.media.matvector.koreabatch.client.my_paperless.bean.DevicesCustomConfigurationBean;
import com.hzdesk.media.matvector.koreabatch.client.my_paperless.bean.DevicesManagerBean;
import com.hzdesk.media.matvector.koreabatch.client.my_paperless.config.RBConfig;
import com.hzdesk.media.matvector.koreabatch.client.my_paperless.custom_view.BrushSizeView;
import com.hzdesk.media.matvector.koreabatch.client.my_paperless.fragment.fragment_contract.IMouseSetContract;
import com.hzdesk.media.matvector.koreabatch.client.my_paperless.inter.IonClickedItemListenter;
import com.hzdesk.media.matvector.koreabatch.client.my_paperless.logic.modle.MouseSetMolde;
import com.hzdesk.media.matvector.koreabatch.client.my_paperless.utils.JsonUitl;
import com.hzdesk.media.matvector.koreabatch.client.my_paperless.utils.RecyclerViewUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;

import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Stack;

import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by Administrator on 2018/8/14.
 * 杭州席媒科技有限公司  Developers  刘传华  10
 * 佛祖镇楼 bug辟易
 */

public class MouseSetPersenter implements IMouseSetContract.IMouseSetPersenter {
    private String TAG = MouseSetPersenter.class.getSimpleName();
    private IMouseSetContract.IMouseSetView mIMouseSetView;
    private IMouseSetContract.IMouseSetMolde mIMouseSetMolde;
    private String[]  arr = new String[]{"red_line","orange_line","yellow_line","green_line","sky_blue_line","blue_line","puple_line","black_line"};
    private List<String> datalist_1 = new LinkedList<>(Arrays.asList("红", "橙", "黄", "绿", "天蓝", "蓝", "紫", "黑"));
    private PopupWindow popup;
    private int selector = 3;
    private TextView tv_cancel;
    private TextView tv_confirm;
    private RecyclerView my_recyclerview;
    private CursorColorAdapter cursorColorAdapter;
    private List<Integer> mlist;
    private Handler handler = new Handler();

    public MouseSetPersenter(IMouseSetContract.IMouseSetView mIMouseSetView) {
        this.mIMouseSetView = mIMouseSetView;
        mIMouseSetMolde = new MouseSetMolde();
    }

    @Override
    public void initTitle() {
        mIMouseSetView.showTitle();
    }

    @Override
    public void onCkleckUserName() {
        mIMouseSetView.toChangeName();
    }

    @Override
    public void onCkicledBrushSize(Context context) {
        View view = View.inflate(context, R.layout.brush_size_select_layout, null);
        findview(view);
        popup = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT);
        popup.setAnimationStyle(R.style.ActionSheetDialogAnimation);
        popup.setOutsideTouchable(true);
        popup.setOutsideTouchable(true);
        popup.setTouchable(true);
        popup.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        popup.setFocusable(true);
        popup.setTouchable(true);
        popup.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        popup.showAtLocation(view, Gravity.CENTER,0,0);
    }

    private void findview(View view) {
        TextView tv_cancel =  view.findViewById(R.id.brush_size_select_layout_tv_cancel);
        TextView tv_confirm =  view.findViewById(R.id.brush_size_select_layout_tv_confirm);
        final BrushSizeView bsv_three =  view.findViewById(R.id.brush_size_select_layout_bsv_three);
        final BrushSizeView bsv_five =  view.findViewById(R.id.brush_size_select_layout_bsv_five);
        final BrushSizeView bsv_seven =  view.findViewById(R.id.brush_size_select_layout_bsv_seven);
        final BrushSizeView bsv_nine =  view.findViewById(R.id.brush_size_select_layout_bsv_nine);
        hidenView(bsv_three,bsv_five,bsv_seven,bsv_nine);
        // todo selector 显示具体的BrushSizeView
        try {
            int   BrushSize = Integer.parseInt(mIMouseSetView.getBrushSize());
            selectOne(bsv_three, bsv_five, bsv_seven, bsv_nine,BrushSize);
        } catch (NumberFormatException e) {}

        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(popup != null ){
                    popup.dismiss();
                }
            }
        });

        tv_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(popup != null ){
                    // todo 需要知道选中了哪个？ 通过常量控制
                    hidenView(bsv_three,bsv_five,bsv_seven,bsv_nine);
                    mIMouseSetView.setBrushSize(selector+"");
                    selectOne(bsv_three, bsv_five, bsv_seven, bsv_nine,selector);
                    popup.dismiss();
                }
            }
        });
        bsv_three.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                hidenView(bsv_three,bsv_five,bsv_seven,bsv_nine);
                showView(bsv_three);
                selector = 3;
            }
        });
        bsv_five.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                hidenView(bsv_three,bsv_five,bsv_seven,bsv_nine);
                showView(bsv_five);
                selector = 5;
            }
        });
        bsv_seven.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                hidenView(bsv_three,bsv_five,bsv_seven,bsv_nine);
                showView(bsv_seven);
                selector = 7;
            }
        });
        bsv_nine.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                hidenView(bsv_three,bsv_five,bsv_seven,bsv_nine);
                showView(bsv_nine);
                selector = 9;
            }
        });

    }

    private void selectOne(BrushSizeView bsv_three, BrushSizeView bsv_five, BrushSizeView bsv_seven, BrushSizeView bsv_nine,int BrushSize) {
            switch (BrushSize){
                case 3:
                    showView(bsv_three);
                    break;
                case 5:
                    showView(bsv_five);
                    break;
                case 7:
                    showView(bsv_seven);
                    break;
                case 9:
                    showView(bsv_nine);
                    break;
            }
    }

    /**
     * @desc 全部显示
     * */
    private void hidenView(BrushSizeView bsv_three, BrushSizeView bsv_five, BrushSizeView bsv_seven, BrushSizeView bsv_nine) {
        bsv_three.hidenSelect();
        bsv_five.hidenSelect();
        bsv_seven.hidenSelect();
        bsv_nine.hidenSelect();
    }
    /**
     * @desc 控制某个显示
     * */
    private void showView(BrushSizeView bsv){
        bsv.showSelect();
    }
    @Override
    public void onCkicledBrushColor() {

    }
    /**
     * @desc 点击光标颜色
     * */
    @Override
    public void onClickedCursorColor(Context context) {
        View view = View.inflate(context, R.layout.cursor_color_select_layout, null);
        findCursorView(view,context);
        popup = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT);
        popup.setAnimationStyle(R.style.ActionSheetDialogAnimation);
        popup.setOutsideTouchable(true);
        popup.setOutsideTouchable(true);
        popup.setTouchable(true);
        popup.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        popup.setFocusable(true);
        popup.setTouchable(true);
        popup.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        popup.showAtLocation(view, Gravity.CENTER,0,0);
    }
    /***
     * @desc 查找光标颜色
     * */
    private void findCursorView(View view,Context context) {
        tv_cancel = view.findViewById(R.id.cursor_color_select_layout_tv_cancel);
        tv_confirm = view.findViewById(R.id.cursor_color_select_layout_tv_confirm);
        my_recyclerview = view.findViewById(R.id.cursor_color_select_layout_my_recyclerview);
        RecyclerViewUtils mRecyclerViewUtils =   new RecyclerViewUtils();
        cursorColorAdapter = new CursorColorAdapter<Integer>(context);
        mRecyclerViewUtils.initView(my_recyclerview,1,context, cursorColorAdapter);
        addDate();
        setDevicesManagerAdapterListener(cursorColorAdapter);

        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(popup != null){
                    popup.dismiss();
                }
            }
        });
        tv_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(popup != null){
                    if(cursorColorAdapter != null){
                       int postion =  cursorColorAdapter.getColorIndex();
                       if(mlist != null){
                           mIMouseSetView.setCursorColor(datalist_1.get(postion));
                       }
                    }
                    popup.dismiss();
                }
            }
        });
    }

    private void addDate() {
        mlist = new ArrayList<>();
        mlist.add(Color.parseColor("#ff0000"));
        mlist.add(Color.parseColor("#ff9600"));
        mlist.add(Color.parseColor("#ffff00"));
        mlist.add(Color.parseColor("#00ff00"));
        mlist.add(Color.parseColor("#87ceeb"));
        mlist.add(Color.parseColor("#0000ff"));
        mlist.add(Color.parseColor("#ff00ff"));
        mlist.add(Color.parseColor("#000000"));
        cursorColorAdapter.AddItemDate(mlist);
    }

    /**
     * @desc 设置监听
     * */
    private void setDevicesManagerAdapterListener(final CursorColorAdapter managerAdapter) {
        managerAdapter.setmIonClickedItemListenter(new IonClickedItemListenter() {
            @Override
            public void onClickedItem(View view) {
            if(my_recyclerview != null){
             int postion =    my_recyclerview.getChildLayoutPosition(view);
                managerAdapter.updateColr(postion);
            }
            }

            @Override
            public void onClickedFist(int postion) {


            }

            @Override
            public void onClickedSecond(int postion) {

            }
        });
    }
    @Override
    public void isDisable() {

    }

    @Override
    public void initDate(Context context, DevicesCustomConfigurationBean.DeviceMousesBean bean) {
        if(bean != null){
          String name =   bean.getName();
          if(name != null && !TextUtils.isEmpty(name)){
              mIMouseSetView.setUserName(name);
          }
          int BrushSize =   bean.getBrushSize();
            mIMouseSetView.setBrushSize(BrushSize+"");
            String brushColor = bean.getBrushColor();
            if(brushColor != null && !TextUtils.isEmpty(brushColor)){
                // 对brushColor 处理
                mIMouseSetView.setBrushColor(brushColor);
            }
           String CursorColor =  bean.getCursorColor();
            if(CursorColor != null){
                for (int i = 0; i < arr.length; i++) {
                    String color = arr[i];
                    if(color != null && color.equals(CursorColor)){
                        mIMouseSetView.setCursorColor(datalist_1.get(i));
                    }
                }
            }
          int dismouse =   bean.getDisMouse();
            if(dismouse == 1){
                mIMouseSetView.hidenDisable();
            }else if(dismouse == 2){
                mIMouseSetView.showDisable();
            }
        }
    }

    @Override
    public void saveDate(Context context,DevicesCustomConfigurationBean.DeviceMousesBean bean,int postion,String deviceId) {
      String devicesAttId =deviceId;
      String disMouse  = "2";
      String id  = "";
      if(bean != null ){
          devicesAttId =  bean.getDeviceAttId();
          id = bean.getId();
      }
      String  cursorColor = "#009887";
       String BrushSize =  mIMouseSetView.getBrushSize();
        String userNmae = mIMouseSetView.getUserName();
        String BrushColor =mIMouseSetView.getBrushColor();

        submitDate(devicesAttId,postion,disMouse,context,id,cursorColor,BrushSize,userNmae,BrushColor);
    }

    private void submitDate(String devicesAttId, int postion, String disMouse, Context context, String id, String cursorColor, String brushSize, String userNmae,String BrushColor) {
        OkHttpUtils
                .post()
                .url(RBConfig.HOST_IP+RBConfig.ADD_OR_CHANGE_CONGFIG_FILE)
                .addHeader("sessionId",mIMouseSetMolde.getToken(context))
                .addParams("deviceAttId", devicesAttId)
                .addParams("cursorColor", cursorColor)
                .addParams("brushSize", brushSize)
                .addParams("disMouse", disMouse)
                .addParams("mouseNum", (postion+1)+"")
                .addParams("name", userNmae)
                .addParams("id", id)
                .addParams("brushColor", BrushColor+"")
                .build()
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(Response response, int id) throws Exception {
                       //  Log.e(TAG, "loadRecyclerViewDate:token ==sdg111===> "+ response.body().string());
                        String NetWorkResponse = JsonUitl.NetWorkResponse(response);
                        if(NetWorkResponse != null){
                            JSONObject object = JsonUitl.NetworkResponseDateDeal(NetWorkResponse);
                            if(object != null){
                                int codo = JsonUitl.getParsinCode(object);
                                final String normalDate = JsonUitl.getStringDateFeld(object);
                                if(codo == 100){
                                    //Type type = new TypeToken<List<DevicesCustomConfigurationBean>>(){}.getType();
                                    handler.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            mIMouseSetView.tofinshPager();

                                            // todo 返回通知刷新
                                        }
                                    });
                                }
                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        mIMouseSetView.showToastMassage(normalDate);
                                    }
                                });
                            }
                        }
                        return null;
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                mIMouseSetView.showToastMassage("保存鼠标配置失败！");
                            }
                        });
                    }

                    @Override
                    public void onResponse(Object response, int id) {

                    }
                });

    }
}
